package com.zatech.cgnci.project.base.result;

import com.zatech.cgnci.project.base.enums.ResponseCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import java.io.Serializable;
import java.util.Objects;


/**
 * 返回消息实体类
 */
@Slf4j
public final class Result<T> implements Serializable {

    private static final long serialVersionUID = 8895746140709342879L;

    private String requestId; // 请求id

    private boolean success; // 是否成功

    private String code; // 错误代码

    private String msg; // 返回信息

    private T data; // 封装返回数据


    private Result() {
    }

    private Result(T object) {
        this(ResponseCodeEnum.HTTP_REQUEST_SUCCESS, object);
    }

    private Result(ResponseCodeEnum responseCodeEnum, T object) {
        this(responseCodeEnum.getCode(), responseCodeEnum.getMsg(), object);
    }

    public Result(ResponseCodeEnum responseCodeEnum, String msg) {
        this(responseCodeEnum.getCode(), msg, null);
    }

    public Result(ResponseCodeEnum responseCodeEnum) {
        this(responseCodeEnum.getCode(), responseCodeEnum.getMsg(), null);
    }

    public Result(String errorCode, String msg) {
        this(errorCode, msg, null);
    }

    /**
     * 判断是否成功.
     *
     * @return true成功 false失败
     */
    public boolean codeIsSuccess() {
        return Objects.equals(ResponseCodeEnum.HTTP_REQUEST_SUCCESS.getCode(), this.getCode());
    }




    private Result(String errorCode, String msg, T data) {
        this.requestId = MDC.get("requestId");
        this.code = errorCode;
        this.msg = msg;
        this.data = data;
        if (ResponseCodeEnum.HTTP_REQUEST_SUCCESS.getCode().equals(this.code)) {
            this.success = true;
        } else {
            this.success = false;
        }
    }

    public static <T> Result<T> create(T t) {
        return new Result<>(t);
    }

    public String getRequestId() {
        return requestId;
    }

    public void setRequestId(String requestId) {
        this.requestId = requestId;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String errorCode) {
        this.code = code;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

}